package com.phototodata.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * HTTP 请求服务类
 * 使用 OkHttp3 进行接口调用
 *
 * @author PhotoToData
 */
public class HttpService {

    private static final int CONNECT_TIMEOUT = 30; // 连接超时时间：30秒
    private static final int READ_TIMEOUT = 60;    // 读取超时时间：60秒
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private final OkHttpClient httpClient;
    private final ObjectMapper objectMapper;

    public HttpService() {
        // 创建 OkHttpClient 实例，配置超时时间
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .build();
        this.objectMapper = new ObjectMapper();
    }

    /**
     * 发送 POST 请求
     *
     * @param apiUrl  接口地址
     * @param idCards 身份证号字符串（逗号分隔）
     * @return 响应 JSON 字符串
     * @throws Exception 请求异常
     */
    public String postRequest(String apiUrl, String idCards) throws Exception {
        RequestBody requestBody = null;
        Response response = null;

        try {
            // 构建请求体 JSON
            Map<String, Object> requestData = new HashMap<>();
            Map<String, String> data = new HashMap<>();
            data.put("a0184", idCards);
            requestData.put("data", data);

            String jsonBody = objectMapper.writeValueAsString(requestData);
            requestBody = RequestBody.create(JSON, jsonBody);

            // 创建请求
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .post(requestBody)
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .addHeader("Accept", "application/json")
                    .build();

            // 发送请求并获取响应
            response = httpClient.newCall(request).execute();

            // 检查响应码
            if (!response.isSuccessful()) {
                String errorBody = response.body() != null ? response.body().string() : "无响应内容";
                throw new Exception("接口请求失败，HTTP 状态码：" + response.code() + 
                        "，响应：" + errorBody);
            }

            // 读取响应体
            ResponseBody responseBody = response.body();
            if (responseBody == null) {
                throw new Exception("接口响应为空");
            }

            String responseJson = responseBody.string();
            return responseJson;

        } catch (java.net.SocketTimeoutException e) {
            throw new Exception("接口请求超时：" + e.getMessage(), e);
        } catch (java.net.ConnectException e) {
            throw new Exception("无法连接到接口服务器：" + e.getMessage(), e);
        } catch (IOException e) {
            throw new Exception("接口请求 IO 异常：" + e.getMessage(), e);
        } catch (Exception e) {
            throw new Exception("接口请求异常：" + e.getMessage(), e);
        } finally {
            // 释放响应资源
            if (response != null && response.body() != null) {
                try {
                    response.body().close();
                } catch (Exception e) {
                    // 忽略关闭异常
                }
            }
        }
    }

    /**
     * 关闭 HTTP 客户端（释放资源）
     */
    public void close() {
        if (httpClient != null) {
            httpClient.dispatcher().executorService().shutdown();
            httpClient.connectionPool().evictAll();
        }
    }
}

